package dy.com.第7章服务器优化.Client;

import dy.com.收发并行.Util.CloseUtils;
import dy.com.第7章服务器优化.Client.bean.ServerInfo;

import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class TCPClient2 {
    private final Socket socket;
    private final ReadHandler readHandler;
    private final PrintStream printStream;

    public TCPClient2(Socket socket, ReadHandler readHandler) throws IOException {
        this.socket = socket;
        this.readHandler = readHandler;
        printStream = new PrintStream(socket.getOutputStream());
    }

    //退出
    void exit(){
        readHandler.exit();
        CloseUtils.close(printStream);
        CloseUtils.close(socket);
    }
    //用于输出
    public void send(String str){
        printStream.println(str);
    }

    static TCPClient2 startWith(ServerInfo serverInfo) throws IOException {
        Socket socket = new Socket();
        socket.setSoTimeout(3000);
        //连接
        socket.connect(new InetSocketAddress(InetAddress.getByName(serverInfo.getIp()), serverInfo.getPort()), 3000);

        System.out.println("客户端已经发起连接");
        //启动读线程
        try{
            ReadHandler readHandler = new ReadHandler(socket.getInputStream());
            readHandler.start();
            return new TCPClient2(socket,readHandler);
        }catch (Exception e){
            System.out.println("连接异常");
            CloseUtils.close(socket);
        }
        return null;

    }


    private static class ReadHandler extends Thread {
        InputStream inputStream;
        boolean finish = false;

        ReadHandler(InputStream inputStream) {
            this.inputStream = inputStream;
        }
        BufferedReader bufferedReader = null;
        @Override
        public void run() {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                while (!finish) {

                    String str = null;
                    try {

                        str = bufferedReader.readLine();
                    } catch (SocketTimeoutException e) {
                        continue;
                    }

                    if (str == null) {
                        System.out.println("连接已经关闭，无法读取数值");
                        break;
                    } else {
                        System.out.println(str);
                    }


                }
            }catch (Exception e){
                if (!finish) {
                    e.printStackTrace();
                }
            }
            finally {
                CloseUtils.close(inputStream);
                CloseUtils.close(bufferedReader);
            }

        }

        void exit() {
            finish = true;
            CloseUtils.close(inputStream);
            CloseUtils.close(bufferedReader);
        }
    }
}
